using System;
using System.IO;
using System.Text.Json;
using System.Threading.Tasks;

namespace DocumentCreationSystem
{
    /// <summary>
    /// 快速AI服务状态检查工具
    /// </summary>
    public class QuickAIServiceCheck
    {
        public static async Task RunQuickCheckAsync()
        {
            Console.WriteLine("=== 快速AI服务状态检查 ===");
            Console.WriteLine();

            try
            {
                // 1. 检查配置文件
                Console.WriteLine("1. 检查配置文件...");
                await CheckConfigurationFiles();
                Console.WriteLine();

                // 2. 检查服务连接
                Console.WriteLine("2. 检查服务连接...");
                await CheckServiceConnections();
                Console.WriteLine();

                // 3. 提供解决建议
                Console.WriteLine("3. 解决建议...");
                ProvideSolutions();

            }
            catch (Exception ex)
            {
                Console.WriteLine($"检查过程中发生错误: {ex.Message}");
            }

            Console.WriteLine();
            Console.WriteLine("=== 检查完成 ===");
        }

        private static async Task CheckConfigurationFiles()
        {
            // 检查appsettings.json
            var appSettingsPath = "appsettings.json";
            if (File.Exists(appSettingsPath))
            {
                Console.WriteLine("✓ appsettings.json 存在");
                try
                {
                    var content = await File.ReadAllTextAsync(appSettingsPath);
                    var json = JsonDocument.Parse(content);
                    
                    if (json.RootElement.TryGetProperty("AI", out var aiSection))
                    {
                        Console.WriteLine("✓ AI配置节存在");
                        
                        if (aiSection.TryGetProperty("DefaultProvider", out var provider))
                        {
                            Console.WriteLine($"  默认提供者: {provider.GetString()}");
                        }
                        else
                        {
                            Console.WriteLine("⚠ 未设置默认提供者");
                        }
                    }
                    else
                    {
                        Console.WriteLine("✗ AI配置节不存在");
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"✗ 配置文件解析失败: {ex.Message}");
                }
            }
            else
            {
                Console.WriteLine("✗ appsettings.json 不存在");
            }

            // 检查AI模型配置文件
            var aiConfigPath = "ai_model_config.json";
            if (File.Exists(aiConfigPath))
            {
                Console.WriteLine("✓ AI模型配置文件存在");
                try
                {
                    var content = await File.ReadAllTextAsync(aiConfigPath);
                    var json = JsonDocument.Parse(content);
                    
                    if (json.RootElement.TryGetProperty("Platform", out var platform))
                    {
                        Console.WriteLine($"  配置平台: {platform.GetString()}");
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"⚠ AI配置文件解析失败: {ex.Message}");
                }
            }
            else
            {
                Console.WriteLine("⚠ AI模型配置文件不存在（可能未配置）");
            }
        }

        private static async Task CheckServiceConnections()
        {
            // 检查Ollama
            Console.WriteLine("检查Ollama服务 (http://localhost:11434)...");
            await CheckHttpService("http://localhost:11434/api/tags", "Ollama");

            // 检查LM Studio
            Console.WriteLine("检查LM Studio服务 (http://localhost:1234)...");
            await CheckHttpService("http://localhost:1234/v1/models", "LM Studio");
        }

        private static async Task CheckHttpService(string url, string serviceName)
        {
            try
            {
                using var client = new System.Net.Http.HttpClient();
                client.Timeout = TimeSpan.FromSeconds(5);
                
                var response = await client.GetAsync(url);
                if (response.IsSuccessStatusCode)
                {
                    Console.WriteLine($"✓ {serviceName} 服务正常");
                }
                else
                {
                    Console.WriteLine($"⚠ {serviceName} 服务响应异常: {response.StatusCode}");
                }
            }
            catch (System.Net.Http.HttpRequestException)
            {
                Console.WriteLine($"✗ {serviceName} 服务不可达（可能未启动）");
            }
            catch (TaskCanceledException)
            {
                Console.WriteLine($"✗ {serviceName} 服务响应超时");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"✗ {serviceName} 检查失败: {ex.Message}");
            }
        }

        private static void ProvideSolutions()
        {
            Console.WriteLine("根据检查结果，建议采取以下措施：");
            Console.WriteLine();
            
            Console.WriteLine("如果AI配置文件不存在或配置不完整：");
            Console.WriteLine("  1. 启动应用程序");
            Console.WriteLine("  2. 打开 AI模型配置 窗口");
            Console.WriteLine("  3. 选择平台并配置模型");
            Console.WriteLine("  4. 测试连接并保存");
            Console.WriteLine();
            
            Console.WriteLine("如果Ollama服务不可达：");
            Console.WriteLine("  1. 安装并启动Ollama");
            Console.WriteLine("  2. 下载所需模型: ollama pull llama3.2");
            Console.WriteLine("  3. 确认服务运行在端口11434");
            Console.WriteLine();
            
            Console.WriteLine("如果LM Studio服务不可达：");
            Console.WriteLine("  1. 启动LM Studio应用");
            Console.WriteLine("  2. 加载模型到服务器");
            Console.WriteLine("  3. 确认服务运行在端口1234");
            Console.WriteLine();
            
            Console.WriteLine("如果使用在线API（智谱AI/DeepSeek）：");
            Console.WriteLine("  1. 确认API密钥有效");
            Console.WriteLine("  2. 检查网络连接");
            Console.WriteLine("  3. 确认账户余额充足");
        }
    }

    /// <summary>
    /// 快速检查控制台程序
    /// </summary>
    class QuickCheckConsole
    {
        static async Task Main(string[] args)
        {
            Console.WriteLine("AI服务快速状态检查");
            Console.WriteLine("==================");
            Console.WriteLine();

            await QuickAIServiceCheck.RunQuickCheckAsync();

            Console.WriteLine();
            Console.WriteLine("按任意键退出...");
            Console.ReadKey();
        }
    }
}
